package base

import (
	"flag"
	"github.com/widuu/gomysql"
	"github.com/fzzy/radix/redis"
	"github.com/widuu/goini"
	"github.com/fzzy/radix/extra/pool"
	"strconv"
	"fmt"
)

var (
	Masterfile *string = flag.String("master", "", "Use -master <master mysql server config file>")
	Slavefile  *string = flag.String("slave", "", "Use -salve <slave mysql server config file>")
	Redisfile  *string = flag.String("redis", "", "Use -redis <redis server config file>")
	Port       *string = flag.String("port", "", "Use -port <web server port>")
	GinMode    *string = flag.String("mode", "", "Use -mode <web server model='release,debug',default='release'>")
	Master     *gomysql.Model
	Slave      *gomysql.Model
	Redis      *pool.Pool
)

func init() {
	flag.Parse()
	if *Masterfile == "" {
		*Masterfile = "./conf/master.ini"
	}
	if *Slavefile == "" {
		*Slavefile = "./conf/slave.ini"
	}
	if *Redisfile == "" {
		*Redisfile = "./conf/redis.ini"
	}
	if *Port == "" {
		*Port = "8000"
	}
	if *GinMode == "" {
		*GinMode = "release"
	}

	master, merr := gomysql.SetConfig(*Masterfile, "database") //根据配置文件，连接数据库
	if merr != nil {
		ConsoleWrite("数据库主库连接失败，原因"+merr.Error())
		Master = nil
	}else{
		ConsoleWrite("数据库主库获取成功")
		Master = master
	}

	if *Slavefile != "" {
		slave, serr := gomysql.SetConfig(*Slavefile, "database") //根据配置文件，连接数据库
		if serr != nil {
			ConsoleWrite("数据库从库连接失败，原因"+serr.Error())
			ConsoleWrite("数据库主库代替从库使用")
			Slave = Master
		}else{
			ConsoleWrite("数据库从库获取成功")
			Slave = slave
		}
	}

	if *Redisfile != "" {
		conf := goini.SetConfig(*Redisfile)
		addr := conf.GetValue("redis", "addr")

		if addr != "no value" {
			maxpool, merr := strconv.Atoi(conf.GetValue("redis", "maxpool"))
			db, derr := strconv.Atoi(conf.GetValue("redis", "db"))
			if merr != nil {
				maxpool = 10
			}
			if derr != nil {
				db = 0
			}
			df := func(network, addr string) (*redis.Client, error) {
				client, err := redis.Dial(network, addr)
				if err != nil {
					return nil, err
				}
				if err = client.Cmd("SELECT", db).Err; err != nil {
					client.Close()
					return nil, err
				}
				//if err = client.Cmd("AUTH", "SUPERSECRET").Err; err != nil {
				//	client.Close()
				//	return nil, err
				//}
				return client, nil
			}
			p, rerr := pool.NewCustomPool("tcp", addr, maxpool, df)
			if rerr != nil {
				ConsoleWrite("Redis服务器连接失败，原因"+rerr.Error())
			}else{
				ConsoleWrite("Redis数据库获取成功")
				Redis = p
			}
		} else {
			//fmt.Println("Redis配置文件【"+*Redisfile+"】没有找到")
			Redis = nil
		}
	}

}
/**
控制器显示信息
 */
func ConsoleWrite(msg string){
	fmt.Println("[MICR-init]"+msg)
	LoggerWrite("info","[MICR-init]"+msg,nil)
}

